﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using System.Text.RegularExpressions;
using System.Linq;

namespace TRIG_MOD_DASHBOARDS.MyTasks
{
    public partial class MyTasksUserControl : UserControl
    {
        CommonMethods objCls = new CommonMethods();


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                errorMsg.Text = "";
                FormLoadBindData();
            }
            catch (Exception x)
            {
                ErrLos(x);
            }

        }

        private void ErrLos(Exception x)
        {
            SPSite Osite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oWeb = Osite.OpenWeb();
            SPListItem oLstItem = oWeb.Lists.TryGetList("ErrorLogs").AddItem();
            oWeb.AllowUnsafeUpdates = true;
            oLstItem["Errors"] = Convert.ToString(x.Message);
            oLstItem.Update();
            oWeb.AllowUnsafeUpdates = false;
            errorMsg.Text = "No Records found"; errorMsg.ForeColor = System.Drawing.Color.Red;
            Osite.Dispose();
        }

        private void ErrLogs(Exception x)
        {
            SPSite Osite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oWeb = Osite.OpenWeb();
            SPListItem oLstItem = oWeb.Lists.TryGetList("ErrorLogs").AddItem();
            oWeb.AllowUnsafeUpdates = true;
            oLstItem["Errors"] = Convert.ToString(x.Message);
            oLstItem.Update();
            oWeb.AllowUnsafeUpdates = false;
            Osite.Dispose();
        }

        protected void gvMyTasks_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(e.Row.DataItem)))
                        {
                            #region "Get DocTypes"

                            SPList oList = oWeb.Lists.TryGetList(e.Row.Cells[0].Text);
                            if (oList != null)
                            {
                                Guid ListID = new Guid(Convert.ToString(oList.ID));
                                if (!string.IsNullOrEmpty(oList.Title))
                                {
                                    try
                                    {
                                        #region "Get List Item"

                                        SPListItem item = getDocItems(oList, e.Row.Cells[6].Text);
                                        if (item != null)
                                        {
                                            string listurl = string.Empty;
                                            string listViewurl = string.Empty;
                                            if (item.Name == e.Row.Cells[1].Text)
                                            {

                                                try
                                                {
                                                    listurl = "javascript:return DialogDisplay('/Sites/SPContext.Current.Web.Title/_layouts/TRIG_MOD_TECHSUB/CustomEdit.aspx?List=" + ListID + "ID=" + item.ID + "WF=0&0=" + e.Row.Cells[5].Text + " ');";
                                                    string url = oList.DefaultViewUrl;
                                                    string[] splitter = Regex.Split(url, "Forms");
                                                    if (splitter != null)
                                                    {
                                                        url = splitter[0] + item["FileLeafRef"].ToString();
                                                    }
                                                    string hypercountry = string.Format("<" + "a href='" + url + "'>" + item["FileLeafRef"].ToString() + "</a>");
                                                    e.Row.Cells[1].Text = hypercountry;

                                                }
                                                catch (ArgumentException) { }
                                                catch (NullReferenceException) { }
                                                CommonMethods.CreateLinkButton("View", listurl, e, 2, true);
                                            }
                                        }
                                        else
                                        {
                                            e.Row.Cells[1].Text = "No records found";
                                        }

                                        #endregion
                                    }
                                    catch (Exception x)
                                    {
                                        ErrLos(x);
                                    }

                                }
                            }
                            else
                            {
                                e.Row.Cells[0].Text = "Library not found";
                            }

                            #endregion
                        }
                    }
                }
            }

            catch (Exception)
            {
                throw;
            }

            if (e.Row.Cells.Count > 5)
            {
                e.Row.Cells[5].Visible = false;
                e.Row.Cells[6].Visible = false;
            }
            else
            {

            }
        }

        protected void gvMyTasks_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvMyTasks.PageIndex = e.NewPageIndex;
            gvMyTasks.DataBind();
        }

        private void FormLoadBindData()
        {
            string LastAssignedUser = null;
            using (SPSite osite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = osite.OpenWeb())
                {
                    DataTable ToShowDt = CommonMethods.CreateDataColumns("DocumentType", "Title", "Related Content", "Status", "Last Reviewer/Last Approver", "TaskID", "DocID");
                    DataTable dtN = CommonMethods.GetItemsOfSpecificTypeFromWeb(SPContext.Current.Site.ID, oWeb.ID, WFStatus("Not Started"), SPListTemplateType.Tasks);
                    if (dtN.Rows.Count > 0)
                    {
                        try
                        {
                            SPFieldUserValue ofldval = null;
                            SPListItem lstim2 = null;
                            foreach (DataRow item in dtN.Rows)
                            {
                                SPListItem lstim = oWeb.Lists[new Guid(item[0].ToString())].GetItemById(int.Parse(item[2].ToString()));
                                SPQuery qry = new SPQuery();
                                qry.Query = "<Where><And><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Completed</Value></Eq><IsNotNull><FieldRef Name=\"AssignedTo\" />" +
                                    "</IsNotNull></And></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";

                                SPListItem oLstItem = oWeb.Lists[new Guid(item[0].ToString())].GetItems(qry)[0];

                                if (ListExist(oWeb, lstim["DocLibID"].ToString()))
                                {
                                    if (oLstItem.ListItems.Count > 0)
                                    {
                                        ofldval = new SPFieldUserValue(oWeb, Convert.ToString(oLstItem["Assigned To"]));

                                        string user = ofldval.LookupValue; string[] users = user.Split('\\'); var e = from s in users select s; int c = e.Count();
                                        if (c > 1) LastAssignedUser = users[1]; else LastAssignedUser = user;
                                    }

                                    lstim2 = getDocItems(oWeb, lstim, lstim["DocLibID"].ToString(), lstim["DocID"].ToString());

                                    if (lstim2 != null)
                                        if (lstim2.ParentList.Title != "Inspection Request")
                                            ToShowDt.Rows.Add(lstim2.ParentList.Title, lstim2["FileLeafRef"], lstim["Title"], lstim["Status"], LastAssignedUser + "   " + lstim["Modified"], lstim["WFOrder"], lstim["DocID"]);
                                        else
                                            if (lstim2.ParentList.Title != "Inspection Request")
                                                ToShowDt.Rows.Add(lstim2.ParentList.Title, "-", lstim["Title"], lstim["Status"], LastAssignedUser + "   " + lstim["Modified"], lstim["WFOrder"], lstim["DocID"]);
                                }
                                else
                                {
                                    ToShowDt.Rows.Add("Library not found", "-", lstim["Title"], lstim["Status"], LastAssignedUser + "   " + lstim["Modified"], lstim["WFOrder"], lstim["DocID"]);
                                }
                            }

                            gvMyTasks.DataSource = ToShowDt;
                            gvMyTasks.DataBind();
                            gvMyTasks.HeaderRow.Cells[5].Visible = false;
                            gvMyTasks.HeaderRow.Cells[6].Visible = false;
                            for (int i = 0; i < gvMyTasks.Rows.Count; i++)
                            {
                                gvMyTasks.Rows[i].Cells[5].Visible = false;
                                gvMyTasks.Rows[i].Cells[6].Visible = false;
                            }
                            gvMyTasks.Visible = true;
                        }
                        catch (Exception x)
                        {
                            ErrLos(x);
                        }


                    }
                    else
                    {
                        errorMsg.Text = "No Records found"; errorMsg.ForeColor = System.Drawing.Color.Green;
                    }

                }
            }
        }

        private bool ListExist(SPWeb oWeb, string guid)
        {
            try
            {
                SPList ckList = oWeb.Lists[new Guid(guid)];
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private SPListItem getDocItems(SPList oList, string DocID)
        {
            try
            {
                return oList.Items.GetItemById(int.Parse(DocID));
            }
            catch (Exception x)
            {
                ErrLogs(x);
                return null;
            }

        }

        private SPListItem getDocItems(SPWeb oWeb, SPListItem lstim, string DocLibID, string DocID)
        {
            SPListItem lstim2 = null;
            try
            {
                lstim2 = oWeb.Lists[new Guid(lstim["DocLibID"].ToString())].GetItemById(int.Parse(lstim["DocID"].ToString()));
                return lstim2;
            }
            catch (Exception x)
            {
                ErrLogs(x);
                return null;
            }

        }

        private static string WFStatus(string wfStatus)
        {
            return "<Where><And><Eq><FieldRef Name=\"AssignedTo\" /><Value Type=\"User\">" + SPContext.Current.Web.CurrentUser.LoginName + "</Value></Eq><Eq><FieldRef Name=\"Status\" />" +
                "<Value Type=\"Choice\">" + wfStatus + "</Value></Eq></And></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";

        }


    }
}
